# 75. 堆内存申请

75

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});
let mallocSize;
let usedMemory = [];
rl.on('line', function(line) {
    if (!mallocSize) {
        mallocSize = parseInt(line);
        if (mallocSize <= 0 || mallocSize > 100) {
            console.log(-1);
            return;
        }
    } else {
        usedMemory.push(line.split(' ').map(Number));
    }
});
rl.on('close', () => {
    usedMemory.sort((a, b) => a[0] - b[0]);
    let start = 0;
    let bestFitStart = -1;
    let minSizeDiff = Infinity;

    for(let block of usedMemory) {
        let blockStart = block[0];
        let blockSize = block[1];
        if (blockStart < start || blockSize <= 0 || blockStart + blockSize > 100) {
            console.log(-1);
            return;
        }
        let free = blockStart - start;
        if (mallocSize <= free && (free - mallocSize) < minSizeDiff) {
            bestFitStart = start;
            minSizeDiff = free - mallocSize;
        }
        start = blockStart + blockSize;
    }

    if (100 - start >= mallocSize && (100 - start - mallocSize) < minSizeDiff) {
        bestFitStart = start;
    }
    conosle.log(bestFitStart);
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44